import pygame, sys, math, random, time

pygame.init()

from Block import Block
from Player import Player
from HardBlock import HardBlock
from Enemy import Enemy
from Background import Background
from Bullet import Bullet
from transportblock import TransportBlock

clock = pygame.time.Clock()

width = 800
height = 600
size = width, height

blocksize = [50,50]
playersize = [40,40]

screen = pygame.display.set_mode(size)
bgColor = r,g,b = 0,0,0

blocks = pygame.sprite.Group()
transportBlocks = pygame.sprite.Group()
bullets = pygame.sprite.Group()
hardBlocks = pygame.sprite.Group()
enemies = pygame.sprite.Group()
backgrounds = pygame.sprite.Group()
players = pygame.sprite.Group()
all = pygame.sprite.OrderedUpdates()

Player.containers = (all, players)
Bullet.containers = (all, bullets)
Block.containers = (all, blocks)
HardBlock.containers = (all, hardBlocks, blocks)
Enemy.containers = (all, enemies)
Background.containers = (all, blocks)
TransportBlock.containers = (all, transportBlocks)


bg = Background("rsc/bg/mainbg.png", size)

def loadLevel(level, playerHealth):
    f = open(level+".lvl", 'r')
    lines = f.readlines()
    f.close()
    
    newlines = []
    
    for line in lines:
        newline = ""
        for c in line:
            if c != "\n":
                newline += c
        newlines += [newline]
        
    for line in newlines:
        print line
    
    for y, line in enumerate(newlines):
        for x, c in enumerate(line):
            if c == "#":
                HardBlock("rsc/blocks/mainBlock.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)
            elif c == "p":
                Block("rsc/blocks/purple.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)
            elif c == "b":
                Block("rsc/blocks/blue.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)
            elif c == "k":
                Block("rsc/blocks/wood crate.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)
            elif c == "t":
                Block("rsc/blocks/Prison-Cells.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)
            elif c == "a":
                TransportBlock([(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)   
    
    f = open(level+".tng", 'r')
    lines = f.readlines()
    f.close()
    
    newlines = []
    
    for line in lines:
        newline = ""
        for c in line:
            if c != "\n":
                newline += c
        newlines += [newline]
        
    for line in newlines:
        print line
    
    for y, line in enumerate(newlines):
        for x, c in enumerate(line):
            if c == "@":
                player = Player(playerHealth,
                    [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2],
                     playersize,
                     size)
            elif c == "e":
                Enemy("rsc/enemy/red guy.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      playersize)
    for each in all.sprites():
        each.fixLocation(player.offsetx, player.offsety)
     
def loadNextLevel(level):
    print "?????????????????????"
    time.sleep(.5)
    playerHealth = player1.health
    for each in all.sprites():
        each.kill()
    bg = Background("rsc/bg/mainbg.png", size)
    screen.blit(bg.image, bg.rect)
    loadLevel(levels[level], playerHealth)
    return level

levels = ["rsc/levels/level1",
          "rsc/levels/level2",
          "rsc/levels/level3",
          "rsc/levels/level4",
          "rsc/levels/level5",]
level = 0
loadLevel(levels[level], 100)
player1 = players.sprites()[0]

while True:
    while player1.living:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    if level < len(levels)-1:
                        level += 1
                    else:
                        level = 0
                    playerHealth = player1.health
                    for each in all.sprites():
                        each.kill()
                    bg = Background("rsc/bg/mainbg.png", size)
                    screen.blit(bg.image, bg.rect)
                    loadLevel(levels[level], playerHealth)
                    player1 = players.sprites()[0]

                if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
                    player1.direction("right")
                if event.key == pygame.K_a or event.key == pygame.K_LEFT:
                    player1.direction("left")
                if event.key == pygame.K_w or event.key == pygame.K_UP:
                    player1.direction("up")
                if event.key == pygame.K_s or event.key == pygame.K_DOWN:
                    player1.direction("down")
                if event.key == pygame.K_SPACE:
                    player1.direction("jump")  
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
                    player1.direction("stop right")
                if event.key == pygame.K_a or event.key == pygame.K_LEFT:
                    player1.direction("stop left")
                if event.key == pygame.K_w or event.key == pygame.K_UP:
                    player1.direction("stop up")
                if event.key == pygame.K_s or event.key == pygame.K_DOWN:
                    player1.direction("stop down")
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    Bullet(player1.headingx, player1.rect.center) 
                        
        playersHitBlocks = pygame.sprite.groupcollide(players, hardBlocks, False, False)
        playersHitEnemies = pygame.sprite.groupcollide(players, enemies, False, False)
        enemiesHitBlocks = pygame.sprite.groupcollide(enemies, hardBlocks, False, False)
        bulletsHitBlocks = pygame.sprite.groupcollide(bullets, hardBlocks, True, False)
        enemiesHitEnemies = pygame.sprite.groupcollide(enemies, enemies, False, False)
        bulletsHitEnemies = pygame.sprite.groupcollide(bullets, enemies, True, True)
        playersHitTransportBlocks = pygame.sprite.groupcollide(players, transportBlocks, False, False)
         
        for player in playersHitBlocks:
            for block in playersHitBlocks[player]:
                player.collideBlock(block)
       
        for player in playersHitTransportBlocks:
            for block in playersHitTransportBlocks[player]:
                print "---------------------------------"
                time.sleep(.5)
                level = loadNextLevel(level+1)
                player1 = players.sprites()[0]  
  
        for player in playersHitEnemies:
            for enemy in playersHitEnemies[player]:
                player.collideEnemy(enemy)
        
        for enemy in enemiesHitBlocks:
            for block in enemiesHitBlocks[enemy]:
                enemy.collideBlock(block)
                
        for enemy in enemiesHitEnemies:
            for otherEnemy in enemiesHitEnemies[enemy]:
                enemy.collideBlock(otherEnemy)
                
        all.update(size,
                   player1.speedx, 
                   player1.speedy, 
                   player1.scrollingx, 
                   player1.scrollingy,
                   player1.realx,
                   player1.realy)
        
        dirty = all.draw(screen)
        pygame.display.update(dirty)
        pygame.display.flip()
        clock.tick(30)
   
 
    for each in all.sprites():
        each.kill()
    bg = Background("rsc/bg/endscreen.png", size)
 
    while not player1.living:  
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()


   
        all.update(size,
                   player1.speedx, 
                   player1.speedy, 
                   player1.scrollingx, 
                   player1.scrollingy,
                   player1.realx,
                   player1.realy)
        
        dirty = all.draw(screen)
        pygame.display.update(dirty)
        pygame.display.flip()
        clock.tick(30)
   





